package com.zxy.lm.controller;


import com.zxy.lm.entity.Admin;
import com.zxy.lm.entity.Book;
import com.zxy.lm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusi
 * @since 2021-06-22
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping("/updateBook")
    public String updateBook(HttpSession session, Model model, Book book) {
        //管理员才能修改
        Object o = session.getAttribute("admin");
        if (!(o instanceof Admin)) {
            model.addAttribute("almsg", "请先登录");
            return "redirect:/admin/login";
        }
        //更新书
        boolean b = bookService.updateById(book);
        if (b) {
            return "redirect:/admin/queryBook";
        } else {
            model.addAttribute("emsg", "修改失败");
            return "redirect:/admin/editBook";
        }
    }

    @PostMapping("/addBook")
    public String addBook(HttpSession session, Model model, Book book) {
        //管理员才能添加
        Object o = session.getAttribute("admin");
        if (!(o instanceof Admin)) {
            model.addAttribute("almsg", "请先登录");
            return "redirect:/admin/login";
        }
        //设置书id为null，让数据库自增id
        book.setId(null);
        //保存书
        boolean save = bookService.save(book);
        if (save){
            return "redirect:/admin/queryBook";
        }else {
            model.addAttribute("amsg", "保存失败");
            return "redirect:/admin/addBook";
        }
    }
}

